package pl.edu.agh.inpema.core.components.impl;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.jms.JMSException;

import org.apache.log4j.Logger;

import pl.edu.agh.inpema.core.components.ReceiverUtil;
import pl.edu.agh.inpema.core.dataBase.DataBase;
import pl.edu.agh.inpema.core.environment.Environment;
import pl.edu.agh.inpema.core.model.Message;
import pl.edu.agh.inpema.core.model.Profile;
import pl.edu.agh.inpema.core.queue.Queue;
import pl.edu.agh.inpema.core.queue.QueueMessage;

public class ReceiverUtilImpl implements ReceiverUtil {
	
	private String receiverName;
	
	private Set<String> analyzersListeners;
	
	private static Logger logger = Logger.getLogger(ReceiverUtilImpl.class);

	private DataBase dataBase;
	private Queue queue;
	
	public void addMessage(String login, Map<String, String> messageFields) {
		Integer profileId = this.dataBase.getProfileId(new Profile(this.receiverName, login));
		
		if (profileId == null) {
			profileId = this.dataBase.addProfile(new Profile(this.receiverName, login));
		}

		Message message = new Message(profileId);
	
		for (String fieldType : messageFields.keySet()) {
			message.setField(fieldType, messageFields.get(fieldType));
		}
	
		int messageId = this.dataBase.addMessage(message);
	
		//System.out.println(receiverName + ": send message - "+messageId);
	
		logger.info(receiverName + ": send message - "+messageId);
		
		try {
			if (this.analyzersListeners != null) {
				QueueMessage queueMessage = new QueueMessage(this.receiverName, messageId);
				for (String analyzerName : this.analyzersListeners) {
					this.queue.sendMessageToAnalyzer(analyzerName, queueMessage);
				}
			}
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	public String getReceiverName() {
		return this.receiverName;
	}
	
	public void setReceiverName(String name) {
		this.receiverName = name;
	}
	
	public void addAnalazerListener(String analazerName) {
		this.analyzersListeners.add(analazerName);
	}
	
	public void setAnalazerListeners(Set<String> analazerNames) {
		this.analyzersListeners = analazerNames;
	}
	
	public boolean hasAnalazerListener(String analazerName) {
		return this.analyzersListeners.contains(analazerName);
	}
	
	public void removeAnalazerListener(String analazerName) {
		this.analyzersListeners.remove(analazerName);
	}
	
	public void removeAllListeners() {
		this.analyzersListeners = new HashSet<String>();
	}
	
	public Set<String> getAllAnalyzerNames() {
		return this.analyzersListeners;
	}

	public void setDataBase(DataBase dataBase) {
		this.dataBase = dataBase;
	}
	
	public void setQueue(Queue queue) {
		this.queue = queue;
	}	
}
